package logic

import (
	"iot-base/auth/model/iot"
	"iot-base/auth/svc"
	"iot-base/auth/types"
)

type StationLogic struct {
}

func NewStationLogic() *StationLogic {
	return &StationLogic{}
}

func (s *StationLogic) AddStation(param types.ReqAddStation) error {
	data := iot.Stations{
		ParentID: param.ParentId,
		Lat:      param.Lat,
		Lon:      param.Lon,
		Desc:     param.Desc,
		AreaID:   param.AreaId,
		Level:    param.Level,
	}
	data.AutoID()
	data.SName = param.Name
	tx := svc.Dao.GetDb().Begin()
	var err error
	defer func() {
		if f := recover(); f != nil {
			tx.Rollback()
		}
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	// 添加站点
	err = tx.Create(&data).Error
	if err != nil {
		return err
	}
	// 添加设备表
	thing := &iot.Thing{
		UID:          data.UID,
		ModelID:      param.ModelId,
		SName:        data.SName,
		StatusUsed:   1, // 使用中
		ProtocolPath: "",
		BusinessID:   "",
		IsStation:    true,
		Lat:          param.Lat,
		Lon:          param.Lon,
		Level:        int64(param.Level),
		ProxyThingID: "",
	}
	err = tx.Create(&thing).Error
	return err
}

func (s *StationLogic) ModifyStation(param types.ReqMgModifyStation) error {
	data := map[string]interface{}{
		"lat":     param.Lat,
		"lon":     param.Lon,
		"desc":    param.Desc,
		"area_id": param.AreaId,
		"level":   param.Level,
	}
	_ = svc.Dao.TStations.Update(param.StationId, data)
	// 更新设备表
	thing := iot.Thing{
		UID:          param.StationId,
		ModelID:      param.ModelId,
		SName:        param.SName,
		StatusUsed:   param.StatusUsed, // 使用中
		ProtocolPath: "",
		BusinessID:   "",
		IsStation:    true,
		Lat:          param.Lat,
		Lon:          param.Lon,
		Level:        int64(param.Level),
		ProxyThingID: "",
	}
	err := svc.Dao.TThings.Update(thing)
	return err
}
